<template>
  <div>
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="loadNextPageArticle"
      success-text="刷新文章成功"
    >
      <van-list
        v-model="loading"
        @load="loadNextPageArticle"
        offset="0"
        :immediate-check="false"
        :error.sync="error"
        error-text="加载文章失败，点击重新加载"
        :finished="isFinished"
        finished-text="木有了文章了!!!!!!"
      >
        <ArticlesItem
          v-for="item in articles"
          :key="item.art_id"
          :articleInfo="item"
        ></ArticlesItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleAPI } from '@/api'
import ArticlesItem from '@/components/ArticleItem.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticlesItem
  },
  data() {
    return {
      articles: [],
      pre_timestamp: '',
      loading: false,
      isFinished: false,
      error: false,
      refreshLoading: false
    }
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  created() {
    this.getFistPageArtice()
  },
  methods: {
    async getFistPageArtice() {
      try {
        const { data } = await getArticleAPI(this.id, +new Date())
        this.articles = data.data.results
        this.pre_timestamp = data.data.pre_timestamp
        console.log(data)
      } catch (error) {
        this.$toast.fail('获取文章失败,请刷新页面重新获取')
      }
    },
    async loadNextPageArticle() {
      try {
        //发送请求
        const { data } = await getArticleAPI(this.id, this.pre_timestamp)

        const timestamp = data.data.pre_timestamp

        if (timestamp == null) {
          this.isFinished = true
        }
        if (this.refreshLoading) {
          //储存数据
          this.articles.unshift(...data.data.results)
        } else {
          this.articles.push(...data.data.results)
        }

        //更新时间戳
        this.pre_timestamp = timestamp
      } catch (error) {
        this.error = true
      } finally {
        this.loading = false
        this.refreshLoading = false
      }
    }
  }
}
</script>

<style></style>
